<template>
  <n-drawer v-model:show="modelValue.show" :width="600" :height="600" :placement="'bottom'">
    <n-drawer-content :title="toADDFlag ? '添加' : '修改'" closable :mask-closable="false">
      <n-form ref="formRef" :model="formValue" :rules="rules" :size="'medium'" label-placement="left" label-width="auto"
        require-mark-placement="right-hanging">
        <n-grid :cols="2" x-gap="20" y-gap="10">
          <n-form-item-gi label="id" path="id">
            <n-text>
              {{ formValue.id }}
            </n-text>
          </n-form-item-gi>
          <n-form-item-gi label="类型" path="type">
            <n-select v-model:value="formValue.taskLogType" :options="taskLogTypeOptions" @update:value="
              formValue.fieldId = null;
            formValue.stageId = null;
            formValue.taskId = null;
            " />
          </n-form-item-gi>
          <n-form-item-gi label="任务" path="taskId">
            <!--          {{ choose }}-->
            <template v-if="formValue.taskLogType == 1">
              <n-tree-select v-model:value="formValue.fieldId" @update:value="
                formValue.stageId = null;
              formValue.taskId = null;
              getStageSelectFromBack(formValue.fieldId);
              " :options="fieldSelect" filterable />
              <n-select v-model:value="formValue.stageId" @update:value="
                formValue.taskId = null;
              getTaskSelectFromBack(formValue.stageId);
              " :options="stageSelect" filterable />
              <n-select v-model:value="formValue.taskId" :options="taskSelect" filterable />
            </template>
            <template v-if="formValue.taskLogType == 2">
              <n-select v-model:value="formValue.fieldId" @update:value="
                formValue.taskId = null;
              getLifeModeItemSelectFromBack(formValue.fieldId);
              " :options="lifeModeSelect" />
              <n-select v-model:value="formValue.taskId" :options="lifeModeItemSelect" />
            </template>
          </n-form-item-gi>
          <n-form-item-gi label="开始结束时间" path="startTime">
            <MyDatePicker v-model:time="formValue.startTime"></MyDatePicker>
            <MyDatePicker v-model:time="formValue.endTime"></MyDatePicker>
          </n-form-item-gi>
          <n-form-item-gi label="留言" path="markDownFile">
            <n-input v-model:value="formValue.markDownFile" type="textarea" placeholder="记录" />
          </n-form-item-gi>
          <n-form-item-gi label="是否加入回忆" path="isMemory">
            <n-space>
              <n-switch v-model:value="formValue.memory">
                <template #unchecked>回忆</template>
              </n-switch>
              <n-button @click="MyLocation.getLocation()">获取地址</n-button>
            </n-space>

          </n-form-item-gi>
          <n-form-item-gi label="图片" path="picList">
            <!--            <PicShowList v-model="formValue.picList"></PicShowList>-->
          </n-form-item-gi>
          <n-form-item-gi label="视频" path="mediaList">
            <!--            <VedioShowList v-model="formValue.mediaList"></VedioShowList>-->
          </n-form-item-gi>
          <n-form-item-gi>
            <n-button type="primary" @click="handleValidateClick">
              {{ toADDFlag ? "添加" : "修改" }}
            </n-button>
          </n-form-item-gi>
        </n-grid>
        {{ formValue.jsonContent }}
        <template v-if="formValue.memory">
          <MyRichText v-model:title="formValue.title" v-model:jsonContent="formValue.jsonContent"></MyRichText>
        </template>
      </n-form>
    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts" setup>
import UseSurfaceSettingStore from "@/store/modules/surfaceSetting";
import { NForm, NFormItem, NInput, NDrawer, NDrawerContent, NButton, FormInst, useMessage } from "naive-ui";
import { ref, computed, watch, Ref } from "vue";
import { UseConstsStore } from "@/store/modules/consts";
import { TimeMentionModal, TaskLogData, TaskMoreData, StageData, MyLocation } from "@/views/model/model";
import { timestampToDateTime } from "@/utils";
import { post, Response } from "@/api/http";
import {
  addStage,
  addTask, addTaskLog,
  getFieldSelect,
  getGoalSelect,
  getLifeModeItemSelect, getLifeModeSelect,
  getStageSelect,
  getTaskSelect
} from "@/api/url";
import useUserStore from "@/store/modules/user";
import MyTime from "@/views/task/time/MyTime.vue";
import { obj2Map } from "@/utils";
import { renderIcon } from "@/hooks/form";
import { Book } from "@vicons/ionicons5";
import RichText from "@/views/editor/rich-text.vue";
import MyRichText from "@/views/taskoperation/tasklog/MyRichText.vue";
import MyDatePicker from "@/views/task/time/MyDatePicker.vue";

// 全局数据
const useSurfaceSetting = UseSurfaceSettingStore()
const useConsts = UseConstsStore()
const message = useMessage();
const userStore = useUserStore()

// 父组件数据
const props = defineProps<{
  modelValue: {
    show: boolean
    key: Ref<number>
    data: TaskLogData
    [key: string]: any
  }
}>();
const emit = defineEmits(["update:modelValue"]);
const modelValue = computed({
  get: () => props.modelValue,
  set: val => emit("update:modelValue", val),
});

// 页面数据
const toADDFlag = computed(() => {
  return "undefined" == typeof modelValue.value.data.id || modelValue.value.data.id == null || modelValue.value.data.id == 0;
});
const rules = {
  name: {
    required: true,
    message: "请输入名字",
    trigger: ["input"],
  },
};
const formRef = ref<FormInst | null>(null);
const formValue = ref(modelValue.value.data);

watch(modelValue.value, async () => {
  formValue.value = modelValue.value.data
  await getGoalAndFieldSelect()
  // console.log(formValue.value)
  taskLogTypeOptions.value = useConsts.getLabelValue(useConsts.getConsts().taskLogTypeMap)
    .map(u => { return { label: u.label, value: parseInt(u.value), key: parseInt(u.value) } })
});

const taskLogTypeOptions = ref<any>([])
const goalSelect = ref<Array<any>>([]);
const fieldSelect = ref<Array<any>>([]);
const stageSelect = ref<Array<any>>([]);
const taskSelect = ref<Array<any>>([]);
const lifeModeSelect = ref<Array<any>>([]);
const lifeModeItemSelect = ref<Array<any>>([]);
const getLifeModeItemSelectFromBack = async (id: number | null) => {
  if (id) {
    // console.log(id)
    try {
      const data: Response = await post({
        url: getLifeModeItemSelect,
        data: { id: id },
        token: userStore.getToken()
      });
      // console.log(data)
      lifeModeItemSelect.value = data.data.data
      // stageSelect.push(...)
      console.log(lifeModeItemSelect, "+++++++++++++++")
    } catch (e) {
      message.error((e as Error).message)
    } finally {
    }
  }
}
const getTaskSelectFromBack = async (id: number | null) => {
  if (id) {
    // console.log(id)
    try {
      const data: Response = await post({
        url: getTaskSelect,
        data: { id: id },
        token: userStore.getToken()
      });
      // console.log(data)
      taskSelect.value = data.data.data
      // stageSelect.push(...)
      console.log(taskSelect)
    } catch (e) {
      message.error((e as Error).message)
    } finally {
    }
  }
}
const getStageSelectFromBack = async (id: number | null) => {
  if (id) {
    // console.log(id)
    try {
      const data: Response = await post({
        url: getStageSelect,
        data: { id: id },
        token: userStore.getToken()
      });
      // console.log(data)
      stageSelect.value = data.data.data
      // stageSelect.push(...)
      console.log(stageSelect)
    } catch (e) {
      message.error((e as Error).message)
    } finally {
    }
  }
}
const getGoalAndFieldSelect = async () => {
  try {
    const data: Response = await post({
      url: getGoalSelect,
      data: { haveFinish: false },
      token: userStore.getToken()
    });
    // console.log(data)
    goalSelect.value = data.data.data
    // console.log(goalSelect)
  } catch (e) {
    message.error((e as Error).message)
  } finally {
  }
  try {
    const data: Response = await post({
      url: getFieldSelect,
      token: userStore.getToken()
    });
    // console.log(data)
    fieldSelect.value = data.data.data
    // console.log(fieldSelect)
  } catch (e) {
    message.error((e as Error).message)
  } finally {
  }
  try {
    const data: Response = await post({
      url: getLifeModeSelect,
      token: userStore.getToken()
    });
    // console.log(data)
    lifeModeSelect.value = data.data.data
    // console.log(fieldSelect)
  } catch (e) {
    message.error((e as Error).message)
  } finally {
  }
  getStageSelectFromBack(formValue.value.fieldId)
  getTaskSelectFromBack(formValue.value.stageId)
  if (formValue.value.taskLogType === 2) getLifeModeItemSelectFromBack(formValue.value.fieldId)
}


// 添加逻辑
const addItem = async (params: any) => {
  try {
    const data: Response = await post({
      url: addTaskLog,
      data: params,
      token: userStore.getToken()
    });
    // console.log(data)
    message.success(data.msg)
    modelValue.value.show = false
    modelValue.value.key = Date.now()
  } catch (e) {
    message.error((e as Error).message)
  } finally {
  }
}
const handleValidateClick = (e: MouseEvent) => {
  // console.log('toDealRow',toDealRow);
  e.preventDefault();
  formRef.value?.validate(errors => {
    if (!errors) {
      // message.success("Valid");
      // console.log({...formValue.value, ...formValue.value.timeMentionModal})
      // formValue.value.mentionTime = TimeMentionModal.computeMentionTime(formValue.value.timeMentionModal,formValue.value.type)
      const params = { ...formValue.value, toAdd: toADDFlag.value ? 0 : 1 };
      console.log(params, "++++++++++++++++++++", toADDFlag)
      addItem(params);
      // console.log({...formValue.value, ...formValue.value.timeMentionModal})
    } else {
      // console.log(errors);
      //  message.error(errors);
    }
  });

};
</script>

<style scoped>
</style>
